<?php

declare(strict_types=1);

namespace app\common\service\sys;

use app\common\dao\sys\DictDao;
use app\common\traits\ServiceTrait;
use app\common\traits\TreeServiceTrait;

/**
 * 字典
 * @author:kaige
 * @update:2022-06-12
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class DictService
{
  protected $dao = null;

  public function __construct()
  {
    $this->dao = new DictDao();
  }
  use ServiceTrait, TreeServiceTrait;

  /**
   * 获取字典信息 - 接口
   * @param int $id
   * @return mixed
   */
  public function getInfo($id = 0)
  {
    return $this->dao->getInfo($id);
  }

  /**
   * 添加、编辑数据保存
   * @param $data
   * @return array
   */
  public function saveData($data)
  {
    $this->formatData($data);
    return $this->saveForm($data);
  }

  /**
   * 格式化存储的数据
   * @return void
   */
  protected function formatData(&$data)
  {
    $data['is_lock'] = checkon('is_lock', $data);
    $data['type'] = checkon('type', $data);
  }

  /**
   * 获取字典 - 接口
   * @param $ids 字典大类ID,可以是数组 [1,2]
   * @return array 输出子项 数组如 ['typename'=>[a=>1],'typename2'=>[a=>2]]
   */
  public function getDict($ids)
  {
    return $this->dao->getDict($ids);
  }

  /**
   * 取出所有字典--缓存中取
   */
  public static function getDictAll($company_id = 0)
  {
    //  $list = cache('szoa_sysdict');
    //  if(empty($list)){
    $list = (new DictDao())->getDictAll($company_id);
    //    cache('szoa_sysdict',$list);
    //  }
    return $list;
  }

  /**
   * 重写 搜索条件
   * @param $post
   * @return mixed
   */
  public function _list_where($post)
  {
    $where = [];
    $order = ['id' => 'desc'];
    $field = ['*,pid as parentId'];

    if (isset($post['keywords']) && !empty($post['keywords'])) {
      $where[] = ['name|code|value', 'like', '%' . $post['keywords'] . '%'];
    }
    if (isset($post['automatch']) && $post['automatch'] == 1) {
      $order = ['id' => 'asc'];
    }
    if (isset($post['company_id']) && !empty($post['company_id'])) {
      $where[] = ['company_id', '=', $post['company_id']];
    } else {
      $where[] = ['company_id', '=', env('COMPANY_ID', 11)];
    }
    $result['where'] = $where;
    $result['field'] = $field;
    $result['order'] = $order;
    return $result;
  }

  /**
   * 重写 格式化数据
   */
  public function _list_format($list)
  {
    foreach ($list as $k => $v) {
      if (isset($v['handle_time']) && !empty($v['handle_time'])) {
        $list[$k]['handle_time'] = time2str($v['handle_time']);
      }
    }
    return $list;
  }


  /**
   * 获取所有列表树型
   * @return array
   */
  public function getDictTree()
  {
    $data = $this->dao->getListAll(true, ['sort' => 'asc']);
    if ($data) {
      $tree = \app\common\util\TreeUtil::list_to_tree($data, 0, 'id', 'pid', 'children');
      return $tree;
    }
    return [];
  }
}
